#!/usr/bin/python
# -*- coding: utf-8 -*-

# refer to:http://blog.doughellmann.com/2009/04/pymotw-multiprocessing-part-2.html
# 这段代码在rhel6+python2.6上能运行，结果正确。
# 但是在windows7+python2.6来运行则会导致机器内存很快被耗光，
# 任务管理器里能看到迅速产生了大量python进程，最终导致机器内存耗光死机。
# windows7+python3.2来运行也一样
# 具体原因还不太清楚
# 原因找到了，是因为在windows上需要放在if __name__=='__main__':里
# 下面对拷贝来的代码做了点改动，换成用print了，要不然会报另外一个错。

import multiprocessing
import sys


def worker_with(lock, stream):
    with lock:
        print 'Lock acquired via with\n'


def worker_no_with(lock, stream):
    lock.acquire()
    try:
        print 'Lock acquired directly\n'
    finally:
        lock.release()


if __name__ == '__main__':
    lock = multiprocessing.Lock()
    w = multiprocessing.Process(target=worker_with, args=(lock,
                                sys.stdout))
    nw = multiprocessing.Process(target=worker_no_with, args=(lock,
                                 sys.stdout))

    w.start()
    nw.start()

    w.join()
    nw.join()
